<template>
	<view class="my-pay">
		<u-parse :html="html"></u-parse>
		<u-action-sheet :list="paymentList" v-model="paymentShow" @click="choosePayment"></u-action-sheet>
	</view>
</template>

<script>
	function isWeiXin() {
	  let ua = navigator.userAgent.toLowerCase();
	  if (ua.indexOf('micromessenger') != -1) return true;
	  else return false;
	}

	export default {
		props: {
			payUrl: {
				type: String,
				default: "",
			},
			params: {
				type: Object,
				default: () => {},
			},
			show: {
				type: Boolean,
				default: false,
			},
		},
		data() {
			return {
				paymentList: [{
						text: "支付宝支付",
						payment: "alipay",
					},
					{
						text: "微信支付",
						payment: "wechat",
					},
				],
				paymentShow: false,
				html: "",
			};
		},
		mounted() {
			this.paymentShow = this.show;
		},
		watch: {
			show(val) {
				this.paymentShow = this.show;
			},
			paymentShow(val) {
				if (!val) {
					this.$emit("close", false);
				}
			},
		},
		methods: {
			choosePayment(e) {
				let payment = this.paymentList[e].payment;
				this.createOrder(payment);
			},
			createOrder(payment) {
				// #ifdef H5
				let inWeChat = isWeiXin()
				if (inWeChat) {
					this.$msg('请在微信外的浏览器中进行操作')
					return;
				}
				
				this.$u
					.post(this.payUrl, {
						...this.params,
						payment,
						type: "h5",
					})
					.then((res) => {
						let {
							alipay,
							wechat
						} = res.data.result;
						if (alipay) {
							this.html = alipay;
							setTimeout(() => {
								document.forms["alipaysubmit"].submit();
							}, 1);
						} else if (wechat) {
							let { mweb_url } = wechat
							location.href = mweb_url
						}
					});
				// #endif

				// #ifdef APP-PLUS
				this.$u
					.post(this.payUrl, {
						...this.params,
						payment,
					})
					.then((res) => {
						let {
							alipay,
							wechat
						} = res.data.result;
						if (alipay) {
							this.orderInfo = alipay;
							this.gotoPay(payment);
						} else if (wechat) {
							this.orderInfo = JSON.stringify(wechat);
							this.gotoPay("wxpay");
						}
					});
				// #endif
			},
			gotoPay(payment) {
				console.log(payment);
				console.log(this.orderInfo);
				uni.requestPayment({
					provider: payment,
					orderInfo: this.orderInfo,
					success: (res) => {
						console.log("success:" + JSON.stringify(res));
						this.$msg("支付成功");
						this.$emit("success", true);
					},
					fail: (err) => {
						console.log("fail:" + JSON.stringify(err));
						this.$msg("支付错误，或取消");
					},
				});
			},
		},
	};
</script>

<style lang="scss">
</style>
